package com.fight.strive.sys.modules.redis;

import com.fight.strive.sys.modules.web.SpringContextHolder;
import com.fight.strive.sys.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import java.util.Map;

@Slf4j
@Component
public class KeyExpirationListener extends KeyExpirationEventMessageListener {

    public KeyExpirationListener(
            RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        String key = message.toString();
        // 只监控指定的键过期事件
        String prefix = "key_expiration_event:";
        if (StringUtils.startsWith(key, prefix)) {
            // 例如使用@Component("key_expiration_event:scheduler_running") 注解
            // 那个注解的类就会处理 key_expiration_event:scheduler_running 键过期事件
            // 处理类需继承 RedisKeyExpirationHandler
            Map<String, RedisKeyExpirationHandler> redisKeyExpirationHandlerMap =
                    SpringContextHolder.getBeansOfType(RedisKeyExpirationHandler.class);
            if (redisKeyExpirationHandlerMap.containsKey(key)) {
                redisKeyExpirationHandlerMap.get(key).handle(key);
            }
        }
    }
}
